
/* --- 2019-02-18 --- */
!(function ( window, document, $, Vue ) {

	$(function () {

		"use strict";

		/* ===== [ 通用变量和函数 ] ===== */
		var $document = $(document);
		var $window = $(window);
		var $html = $("html");
		var $head = $("head");
		var $body = $("body");
		var www = "/";
		var rootUrl = $html.attr("data-root");
		var teacher_template = "";
		var Dom = function ( selector ) {
			return !!document.querySelector(selector);
		}


		/* ===== [ 移动端的基本支持 ] ===== */
		if ( $.browser.mobile ) {
			$body.width(1300).css({
				transform: "scale(2)",
				transformOrigin: "left top"
			});
		}


		/* ===== [ jquery 对象级别扩展 ] ===== */
		$.fn.extend({
			page: function ( options ) {

				// 默认配置
				var defaults = {
					container: "",
					url: $.noop,
					total: 0,
					every: 0,
					success: $.noop
				};
				var opt = $.extend({}, defaults, options);

				return this.each(function () {
					var $this = $(this);
					var $container = $(opt.container);
					var dataName = "__page-index__";

					// 生成分页按钮
					var perPage = "";
					var pages = opt.total / opt.every;
					pages = pages >= 1 ? (opt.total % opt.every > 0 ? ~~pages + 1 : pages) : pages;
					if ( pages < 1 ) {
						pages = 1;
					}
					for ( var i = 1; i <= pages; i++ ) {
						perPage += '<i class="page-num"><span>' + i + '</span></i>';
					}
					perPage = '<div><div>' + perPage + '</div></div>';
					$this.empty().html('\
						<div>\
							<i class="page-first" title="第一页">«</i>\
							<i class="page-prev" title="上一页">‹</i>\
							' + perPage + '\
							<i class="page-next" title="下一页">›</i>\
							<i class="page-last" title="最后一页">»</i>\
						</div>\
					').addClass("page");

					// 根据是否有内容来决定是否显示分页按钮
					$this[ $.trim($container.html()) === "" ? "hide" : "show" ]();

					var $page = $this.children();
					var $div = $page.find("div > div");
					var $every = $page.find(".page-num");
					var $first = $page.find(".page-first");
					var $last = $page.find(".page-last");
					var $prev = $page.find(".page-prev");
					var $next = $page.find(".page-next");
					var $i = $page.find("i");

					// 添加标记
					$container.data(dataName, 1);

					// 初始状态下第一个按钮处于激活状态
					$every.first().addClass("active");

					// 按钮数量如果超过 10 个
					// 则超出的按钮将以左右滚动的形式出现
					// 页面最多显示 10 个页码按钮
					function moreScroll ( param ) {    
						var max = 10;
						if ( $div.is(":animated") ) {
							return;
						}
						if ( max > pages ) {
						    max = pages;
						}
						if ( max == 0 ) {
						    max = 1;
						}
						var num = pages - max;
						var time = 100;
						var basicNum = 40;
						$div.parent().width(basicNum * max);
						$div.css("width", basicNum * pages + "px");
						var left = parseInt($div.css("marginLeft"));
						switch ( param ) {
						    case "next": 
						        if ( left > -num * basicNum ) {
									$div.animate({
										marginLeft: (left - basicNum) + "px"
									}, time);
						        }
						        break;
						    case "prev":
						        if ( left < 0 ) {
									$div.animate({
										marginLeft: (left + basicNum) + "px"
									}, time);
						        }
						        break;
			       			case "first":
			            		$div.animate({
									marginLeft: 0
			            		}, time);
			            		break;
			       			case "last":
			            		$div.animate({
									marginLeft: (-num * basicNum) + "px"
			            		}, time);
			            		break;  		  
			    		} 
					}
					moreScroll();

					// 切换事件
					var switchFn = function ( index ) {
						$(".page").addClass("page-locking");
						$.getJSON(opt.url(index)).done(function ( response ) {     
							if ( response.status === "1" ) {
								var data = response.data;
								$(opt.container).empty().html(opt.success());

								// 学生端 - 全部课程
								if ( Dom("#page-student-all") ) {
									new Vue({
										el: opt.container,
										data: {
											list: data
										},
										mounted: function () {
											$.imgError($(opt.container).find("img"));
											ChangeButton(opt.container, data);
										}
									});
								}

								// 教师端 - 有日历
								if ( Dom("#live-teacher") || Dom("#manage-teacher") ) {
									var type = ""; 
									new Vue({
										el: "#list-01",
										data: {
											list: data.per_data
										},
										mounted: function () {
											$("i[data-liveurl]").siblings("a,b").addClass("active");
											$("#list-01").find("i:contains('已结束')").addClass("teacher-over").prev().addClass("active").end().next().removeClass("active");
										}
									});

									// 生成 "全国课表"
									new Vue({
										el: "#list-02",
										data: {
											list: data.nat_data
										}
									});
								}

								// 教师端 - 无日历
								if ( Dom("#no-calendar") ) {

									// 判断类别
									var index = $(".teacher-table-area > section:visible").index();   
									var type = "";
									switch ( index ) {
										case 0: type = "all_data"; break;
										case 1: type = "pastry_data"; break;
										case 2: type = "dual_data"; break;
										case 3: type = "live_data"; break;
									}

									var result = "";
									$.each(data[type], function ( i, v ) {
										result += opt.success()(v);
									})
									$(opt.container).empty().html(result);
								}
							}
						}).always(function () {
							$(".page").removeClass("page-locking");
						});
						$container.data(dataName, index);
						$every.eq(index - 1).addClass("active").siblings().removeClass("active");
					}

					var getIndex = function () {
						return $container.data(dataName);
					}

					// 页码切换
					$page.on("click", "i", function () {
						if ( $div.is(":animated") ) {
							return;
					    }
					    var $this = $(this);
						if ( $this.is(".page-num") ) {
							switchFn($(this).index() + 1);
							moreScroll("every");
						}
						if ( $this.is(".page-prev") ) {
							var index = getIndex() - 1;
							if ( index > 0 ) {
								switchFn(index);
								moreScroll("prev");
							}
					    }
					    if ( $this.is(".page-next") ) {
							var index = getIndex() + 1; 
							if ( index < pages + 1 ) {
								switchFn(index);
								moreScroll("next");
							}
				        }
				        if ( $this.is(".page-first") ) {
							if ( getIndex() !== 1 ) {
								switchFn(1);
								moreScroll("first"); 
							}
					    }
					    if ( $this.is(".page-last") ) {
							if ( getIndex() !== pages ) {
								switchFn(pages);
								moreScroll("last");
							}
					    }
					});

					// 调整分页容器的位置
					$this.each(function () {
				        var totalWidth = 0;
				        $(this).children().children().each(function () {
				        	totalWidth += $(this).outerWidth(true);
				        });
				        $(this).width(totalWidth);
					});
				})
			},
			calendar: function ( options ) {
				var defaults = {
					year: null,
					month: null,
					day: 0,
					page: 1
				};
				var opt = $.extend({}, defaults, options);
				var date = new Date();

				// 获取 "年月日"
				var year = opt.year || date.getFullYear();
				var month = opt.month || date.getMonth() + 1;
				var dnow = opt.day;

				// 存储 "年月日"
				var cacheDate = [ year, month, dnow ];

				return this.each(function () {
					var $this = $(this);

					// 添加指定的类
					// 将当前 "年份" 添加到日历顶部
					$this.addClass("calendar").append('<p class="calendar-title"><span>' + year + '</span>年<span><i id="choose-year"></i></p>');
					var $title = $this.find(".calendar-title");

					// 年份选择框
					var years = "";
					for ( var i = year; i < year + 20; i++ ) {
						years += '<span>' + i + '</span>';
					}
					$this.prepend('<div class="calendar-years">' + years + '</div>');
					var $yearsBox = $this.find(".calendar-years");
					$yearsBox.find('span:contains(' + year + ')').addClass("now");
					$("#choose-year").on("click", function () {
						$(".calendar-day").addClass("calendar-cannot-click").find(".has-lesson").remove();
						$yearsBox.fadeIn(200);
					});
					$yearsBox.on("click", "span", function () {
						var _this = $(this);
						$months.find(".active").removeClass("active");
						$(".calendar-day").removeClass("active");
						$yearsBox.fadeOut(200, function () {
							year = parseInt(_this.text());

							// 存入缓存
							cacheDate[ 0 ] = year;
							$title.children().first().text(year);
							$months.css("marginLeft", 0);
							__month__ = 0;
						});
					});

					// 添加月份显示条
					var month_i = "";
					for ( var i = 1; i < 13; i++ ) {
						month_i += '<i>' + i + '月</i>';
					}
					$this.append('\
						<div class="calendar-month-panel">\
							<i class="calendar-month-left"></i>\
							<div>\
								<div class="calendar-months">' + month_i + '</div>\
							</div>\
							<i class="calendar-month-right"></i>\
						</div>\
					');
					var $monthPanel = $this.find(".calendar-month-panel");
					var $months = $monthPanel.find(".calendar-months");
					var $left = $monthPanel.find(".calendar-month-left");
					var $right = $monthPanel.find(".calendar-month-right");
					var $everyMonth = $months.children();

					// 获取月份按钮的宽度
					var basic_month_width = $everyMonth.outerWidth();

					// 设置月份条的左偏移量
					$months.css("marginLeft", '-' + basic_month_width * ((opt.month || month) - 1) + 'px');

					// 给当前月份添加特征类
					$everyMonth.eq((opt.month || month) - 1).addClass("active");

					// 缓存当前月份
					var __month__ = $monthPanel.find(".active").index();

					// 月份左右切换
					$left.on("click", function () {
						var index = __month__;
						index--;
						if ( index >= 0 ) {
							scrollAnimate(index);
						}
					});
					$right.on("click", function () {
						var index = __month__;
						index++;
						if ( index <= 8 ) {
							scrollAnimate(index);
						}
					});
					var scrollAnimate = function ( i ) {
						if ( !$months.is(":animated") ) {
							$months.animate({
								marginLeft: '-' + i * basic_month_width + 'px'
							}, 200, function () {
								__month__ = i;
							});
						}
					}

					// 月份按钮点击事件
					$months.on("click", "i", function () {
						var _this = $(this);
						var text = parseInt(_this.text());

						// 存入缓存
						cacheDate[ 1 ] = text;
						cacheDate[ 2 ] = 0;

						// 月份按钮激活状态切换
						_this.addClass("active").siblings().removeClass("active");

						// 生成对应日期
						createDays(cacheDate[ 0 ], cacheDate[ 1 ]);

						// 点击月份按钮后会向服务器发送请求
						// 为了避免使用者快速连续点击导致频繁发送请求
						// 此处给日历添加一个标识
						// 一旦点击了月份按钮
						// 在发送请求到取得数据这段时间将锁住日历
						// 使其不可点击
						// 直到请求成功或失败后才能解锁
						$this.addClass("calendar-locking");

						if ( Dom("#live-teacher") || Dom("#manage-teacher") ) {
							$("ul").html(teacher_template);
							TeacherAjax(www + "handler/tea_live.aspx?t=cur_month", cacheDate[ 0 ], cacheDate[ 1 ], cacheDate[ 2 ], opt.page);
						}
					});

					// 添加星期显示条
					$this.append('<div class="calendar-week"><i>日</i><i>一</i><i>二</i><i>三</i><i>四</i><i>五</i><i>六</i></div>');

					// 生成日期
					var createDays = function ( y, m ) {

						// 清空现有的日期
						$this.find(".calendar-days").remove();

						// 判断当前月份第一天是星期几
						var firstday = new Date(y, m - 1 , 1).getDay(); 

						// 判断闰年
						var leapYear = function ( y ) {
							return (y % 100 == 0) ? (y % 400 == 0 ? 1 : 0) : (y % 4 == 0 ? 1 : 0);
						}

						// 每月天数数组
						var daysArray = [ 31, 28 + leapYear(y), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];

						// 得到日期
						var days = "";
						for ( var i = 0; i < daysArray[m - 1]; i++ ) {
							days += '<i class="calendar-day calendar-cannot-click" data-num=' + (i + 1) + '>' + (i + 1) + '</i>';
						}

						// 对于月份的第一天不是星期一的情况, 在前面添加占位
						if ( firstday > 0 ) {
							days = new Array(firstday + 1).join('<i class="calendar-placeholder"></i>') + days;
						}

						// 将日期添加进日历
						$this.append('<div class="calendar-days">' + days + '</div>');

						// 日期点击事件
						$(".calendar-days").on("click", ".calendar-day", function () {
							var _this = $(this);
							if ( _this.hasClass("calendar-cannot-click") ) {
								return;
							}
							var text = parseInt(_this.text());

							// 存入缓存
							cacheDate[ 2 ] = text;

							// 点击日期按钮后会向服务器发送请求
							// 为了避免使用者快速连续点击导致频繁发送请求
							// 此处给日历添加一个标识
							// 一旦点击了日期按钮
							// 在发送请求到取得数据这段时间将锁住日历
							// 使其不可点击
							// 直到请求成功或失败后才能解锁
							$this.addClass("calendar-locking");

							// 添加效果
							_this.addClass("active").siblings().removeClass("active");
							_this.find(".has-lesson").hide().end().siblings().find(".has-lesson").show();

							if ( Dom("#live-teacher") || Dom("#manage-teacher") ) {
								$("ul").html(teacher_template);
								TeacherAjax(www + "handler/tea_live.aspx?t=cur_month", cacheDate[ 0 ], cacheDate[ 1 ], cacheDate[ 2 ], opt.page);
							}
						});
					}

					// 默认要自动点击一次当前存储的月份按钮来获取当前年月所对应的日期
					$everyMonth.eq((cacheDate[ 1 ] || month) - 1).trigger("click");
				})
			}
		});


		/* ===== [ jquery 类级别扩展 ] ===== */
		$.extend({
			esc: function ( callback ) {
				$document.on("keyup", function ( event ) {
					if ( event.keyCode === 27 ) {
						callback && callback();
					}
				});
			},
			enter: function ( callback ) {
				$document.on("keyup", function ( event ) {
					if ( event.keyCode === 13 ) {
						callback && callback();
					}
				});
			},
			loginOut: function () {
				$.ajax({
					url: www + "handler/login.ashx",
					type: "POST",
					data: {
						a: "exit",
						u: 0
					},
					dataType: "text"
				}).done(function ( response ) {

					// 退出操作将会删除全部 cookie 
					$.each(document.cookie.match(/[^ =;]+(?=\=)/g), function ( i, v ) {
						$.cookie(v, null, { expires: -1, path: "/" });
					});
									
					// 跳转到指定地址
					window.location.href = response;
				});
			},
			imgError: function ( image ) {
				image.each(function () {
					$(this).on("error", function () {
						$(this).attr("src", rootUrl + "images/placeholder-thumb.png");
					})
				})
			},
			getUrlParam: function ( param, customURL ) {
				var url = (customURL || window.location.href).match(new RegExp(param + "=(.*)"));
				var reg = url ? url[0].replace(new RegExp(param + "="), "") : null;  
				return reg ? (reg.indexOf("&") > 0 ? reg.substring(0, reg.indexOf("&")) : reg) : null;
			},
			alert: function ( options ) {
				var defaults = {
					title: "温馨提示：",
					content: "",
					btnText: "确定",
					customFn: $.noop
				};
				var opt = $.extend({}, defaults, options);
				if ( !$("#public-alert").length ) {
					var duration = 300;
					$body.append('\
						<section id="public-alert">\
							<div>\
								<p>' + opt.title + '</p>\
								<div>' + opt.content + '</div>\
								<span>' + opt.btnText + '</span>\
							</div>\
						</section>\
					');
					var $alert = $("#public-alert");
					var closeAlert = function () {
						$alert.fadeOut(duration).children().animate({
							opacity: 0,
							marginTop: "-40px"
						}, duration, function () {
							$(this).parent().remove();
						});
					}
					$alert.fadeIn(duration).children().width(400).animate({
						opacity: 1,
						marginTop: 0
					}, duration).find("span").last().on("click", function () {
						opt.customFn();
						closeAlert();
					});
					$.esc(closeAlert);
				}
			}
		});


		/* ===== [ 教师端 - ajax 请求 ] ===== */
		var TeacherAjax = function ( url, year, month, day, page ) {
			$.ajax({
				url: url,
				data: {
					y: year,
					m: month,
					d: day,
					pg: page,
					utype: 0
				},
				dataType: "jsonp"
			}).done(function ( response ) {
				var days = response.days;
				var data = response.data;
				if ( response.status === "1" ) {

					// 判断哪天有课
					$.each(days, function ( i, v ) {
						if ( v && !$(".calendar-day").eq(i).find(".has-lesson").length ) {
							$(".calendar-day").eq(i).append('<div class="has-lesson">有课</div>').removeClass("calendar-cannot-click");
						}
					});

					$(".calendar-locking").removeClass("calendar-locking");

					// 生成 "个人课表"
					new Vue({
						el: "#list-01",
						data: {
							list: data.per_data
						},
						mounted: function () {
							$("i[data-liveurl]").siblings("a,b").addClass("active");
							$("#list-01").find("i:contains('已结束')").addClass("teacher-over").prev().addClass("active").end().next().removeClass("active");
							$("#list-01").find("i:contains('未开始')").css("background", "#d7000f").prev().removeClass("active").end().next().addClass("active");
							$(".page-plugin").eq(0).page({
								container: "#list-01 > ul",
								url: function ( page ) {
									return www + "handler/tea_live.aspx?t=cur_month&y=" + year + "&m=" + month + "&d=" + day + "&pg=" + page + "&utype=1&callback=?";
								},
								total: data.per_data_count,
								every: data.pagesize,
								success: function () {
									return teacher_template;
								}
							});
						}
					});

					// 生成 "全国课表"
					new Vue({
						el: "#list-02",
						data: {
							list: data.nat_data
						},
						mounted: function () {
							$(".page-plugin").eq(1).page({
								container: "#list-02 > ul",
								url: function ( page ) {
									return www + "handler/tea_live.aspx?t=cur_month&y=" + year + "&m=" + month + "&d=" + day + "&pg=" + page + "&utype=2&callback=?";
								},
								total: data.nat_data_count,
								every: data.pagesize,
								success: function () {
									return teacher_template;
								}
							});
						}
					});
				}
			});
		}


		/* ===== [ 登录状态判断 ] ===== */
		var loginStatus = function (url) {
		    if (!$.cookie("__etypeseton")) {
		        // 退出操作将会删除全部 cookie 
		        $.each(document.cookie.match(/[^ =;]+(?=\=)/g), function (i, v) {
		            $.cookie(v, null, { expires: -1, path: "/" });
		        });

				window.location.href = (url || "../");
			}
		}


		/* ===== [ 教师端 - 有日历 ] ===== */
		if ( Dom(".public-teacher") ) {

			// 登录状态判断
			loginStatus();

			// 个人课表和全国课表切换
			$("[data-eq]").on("click", function () {
				$(this).addClass("active").siblings().removeClass("active");
				$(".teacher-table-area > section").eq($(this).attr("data-eq")).show().siblings().hide();
			});

			// 存储教师端模板
			teacher_template = $("#list-01 ul").html();

			// 点击 "签到" 按钮和二维码图标
			$document.on("click", ".teacher-sign:contains('签到'), .qrcode-icon", function () {
				var $this = $(this);

				// 二维码图标必须处于激活状态才能执行点击事件
				if ( $this.is(".qrcode-icon:not(.active)") ) {
					return;
				}

				// 发送请求
				$.getJSON(www + "handler/user_sign.aspx?t=tea_b&callback=?", {
					rd: $this.attr("data-rd"),
					tid: $this.attr("data-tid")
				}).done(function ( response ) {
					if ( response.status === "1" ) {
						var data = response.data;
						if ( !Dom(".teacher-public-layer") ) {
							if ( $this.is("i") ) {
								$this.attr("data-liveurl", data.liveurl);
							}

							if ( data.qrcode ) {

								// 二维码弹层
								$body.append('\
									<div class="teacher-public-layer">\
										<div class="teacher-public-layer-content" style="width:500px;height:470px;">\
											<i id="close-teacher-qrcode"></i>\
											<p style="margin-top:40px;text-align:center;font-size:26px;">签到成功</p>\
											<p style="text-align:center;font-size:20px;margin-top:10px;color:#d7000f">已为您获得本次课程二维码和<span style="margin-left:5px;"></span>ID<span style="margin-left:5px;"></span>号</p>\
											<p style="text-align:center;font-size:15px;margin-top:15px;font-weight:bold">' + data.classinfo.name + '<br>' + data.classinfo.taketime + '</p>\
											<div style="width:100%;height:190px;margin-top:30px;overflow:hidden;">\
												<div class="teacher-qrcode"></div>\
												<div class="teacher-idcode">\
													<p style="font-size:18px;"><b>ID：</b><i>' + (data.id_pwd && data.id_pwd[0]) + '</i></p>\
													<p style="font-size:18px;"><b>密码：</b><i>' + (data.id_pwd && data.id_pwd[1]) + '</i></p>\
												</div>\
											</div>\
											<button style="display:block;clear:both;margin:30px auto 0 auto;border:none;background:#d7000f;color:#fff;font-size:14px;padding:5px 10px;border-radius:4px;" id="print-qrcode">打印二维码和 ID 密码</button>\
										</div>\
									</div>\
								');

								// 生成二维码
								$(".teacher-qrcode").qrcode({
									render: "canvas",            	// 渲染方式
									width: 380,						// 默认宽度
									height: 380,					// 默认高度
									typeNumber: -1,              	// 计算模式一般默认为 -1
									correctLevel: 2,             	// 二维码纠错级别
									text: data.qrcode,  	        // 二维码内容
									background: "#fff",          	// 背景颜色
									foreground: "#000"           	// 二维码颜色
								});

								// 打印二维码
								$("#print-qrcode").on("click", function () {
									window.print();
								});

								// 显示弹层
								$(".teacher-public-layer").fadeIn(200);

								// 改变按钮状态
								if ( !$this.is(".qrcode-icon") ) {
									$this.text(data.btnname).prev().attr("data-situation", data.conurl).end().siblings("a,b").addClass("active");
									if ( data.btnname === "未开始" ) {
										$this.css("background", "#d7000f").prev().removeClass("active").end().next().addClass("active");
									}
									if ( data.btnname === "已结束" ) {
										$this.addClass("teacher-over").prev().addClass("active").end().next().removeClass("active");
									}
								}
							} else {
								$.alert({
									content: data.msg
								});
							}
						}
					} else {
						$.alert({
							content: response.msg
						});
					}
				});
			});

			// 关闭二维码弹框
			$document.on("click", "#close-teacher-qrcode", function () {
				$(".teacher-public-layer").fadeOut(200, function () {
					$(this).remove();
				});
			});

			// 点击 "立即观看" 按钮
			$document.on("click", ".teacher-sign:contains('立即观看')", function () {
				$("<a>").attr({
					id: "create-link",
					href: $(this).attr("data-liveurl"),
					target: "_blank"
				}).appendTo("body");
				$("#create-link").on("click", function () {
					$(this).remove();
				}).get(0).click();
			});

			// 点击 "学员情况" 链接
			$document.on("click", ".last a[data-utype]", function () {
				if ( !$(this).hasClass("active") ) {
					return;
				}
				var url = $(this).attr("data-situation");
				if ( $(this).attr("data-utype") === "6zb" ) {

					// 如果是 "直播" 则跳转
					window.location.href = url;
				} else {

					// 否则弹出信息框
					var tmpl = function ( param ) {
						return '\
							<li>\
								<div>' + param.name + '</div>\
								<div>' + param.sex + '</div>\
								<div>' + param.phone + '</div>\
								<span class="sign-state ' + (param.sign_status === "未签到" ? "active" : "") + '">' + param.sign_status + '</span>\
							</li>\
						';
					}
					var content = function ( param ) {
						var result = "";
						$.each(param.data, function ( i, v ) {
							result += tmpl(v);
						});
						return result;
					}
					var outer = function ( param ) {
						return '\
							<div class="teacher-public-layer">\
								<div class="teacher-public-layer-content" style="width:1000px;height:580px;">\
									<i></i>\
									<p class="situation-title">\
                                        <span style="margin-right:50px;">' + param.plan_name + '</span>\
										当前班级总人数： <b>' + param.all_peo_num + '</b>\
										已签到人数： <b id="sign-yes">' + param.y_peo_num + '</b>\
										未签到人数： <b id="sign-no">' + param.n_peo_num + '</b>\
									</p>\
									<section class="teacher-table-area" style="width:835px;margin:40px auto 0 auto">\
										<section>\
											<div class="teacher-table-title">\
												<span style="width:160px;">姓名</span>\
												<span>性别</span>\
												<span class="need-after">电话</span>\
											</div>\
											<div id="situation-list">\
												<ul style="min-height:0;">' + content(param) + '</ul>\
											</div>\
										</section>\
									</section>\
								</div>\
							</div>\
						';
					}

					$.getJSON(url + "&callback=?").done(function ( response ) {
						if ( response.status === "1" ) {
							$body.append(outer(response));

							// 添加序号
							var checkStatus = function () {
								var $ul = $("#situation-list").find("ul");
								$ul.children().each(function ( index ) {
									$(this).append('<i class="situation-index">' + (index + 1) + '</i>');
								});
							}
							checkStatus();

							$(".teacher-public-layer").fadeIn(200).find("i").eq(0).on("click", function () {
								$(".teacher-public-layer").fadeOut(200, function () {
									$(this).remove();
								});
							});

							// 实时刷新
							var timer = null;
							var $list = $("#situation-list").find("ul");
							var $yes = $("#sign-yes");
							var $no = $("#sign-no");
							!(function ajaxInit () {
								var thisAjax = $.getJSON(url + '&callback=?', function ( response ) {

									$(".situation-index").remove();
									$list.empty().html(content(response));
									$yes.text(response.y_peo_num + '人');
									$no.text(response.n_peo_num + '人');
									checkStatus();

									// 请求成功后关闭本次请求
									thisAjax.abort();

									// 定时器重置
									window.clearTimeout(timer);

									// 3000ms 后再次发送请求
									timer = window.setTimeout(function () {
										ajaxInit();
									}, 3000);
								});

								// 手动关闭弹窗后自动移除定时器并关闭请求
								if ( !$(".teacher-public-layer").length ) {
									window.clearTimeout(timer);
									thisAjax.abort();
								}
							})();
						} else {
							$.alert({ content: response.msg });
						}
					});
				}
			});
		}


		/* ===== [ 教师端 - 无日历 ] ===== */
		if ( Dom("#no-calendar") ) {

			// 登录状态判断
			loginStatus();

			// 列表模板
			var template = function ( v ) {
				return '\
					<li>\
						<div class="width"><i>' + v.city_name + '</i></div>\
						<div class="width center">' + v.school_name + '</div>\
						<div class="width center">' + v.peo_num + '</div>\
					</li>\
				';
			}

			// 发送请求
			$.getJSON(www + "handler/tea_live.aspx?t=get_stu_status&callback=?", {
				tid: window.location.href.match(/stusum\/([0-9]+)/)[1],
				pg: 1
			}).done(function ( response ) {
				if ( response.status === "1" ) {
					var data = response.data;
					var size = response.data.pagesize;
					var $numElem = $(".get-all-number");
					var list_box = [ "", "", "", "" ];
					var data_box = [ "all_data", "pastry_data", "dual_data", "live_data" ];
					var num_box =  [ "all_stream_count", "pastry_stream_count", "dual_stream_count", "live_stream_count" ]
					var elem_box = [ "#list-01 ul", "#list-02 ul", "#list-03 ul", "#list-04 ul" ];

					// 一次生成四组内容
					list_box.forEach(function ( v, i ) {
						$.each(data[ data_box[ i ] ], function ( index, value ) {
							list_box[ i ] += template(value);
						});
						$(elem_box[ i ]).html(list_box[ i ]);
						$(".page-plugin").eq(i).page({
							container: elem_box[ i ],
							url: function ( page ) {
								return www + "handler/tea_live.aspx?t=get_stu_status&tid=" + window.location.href.match(/stusum\/([0-9]+)/)[1] + "&pg=" + page + "&utype=" + (i + 1) + "&callback=?";
							},
							total: data[ data_box[ i ] + "_count" ],
							every: size,
							success: function () {
								return template;
							}
						});
						$numElem.eq(i).text(data[ num_box[ i ] ]);
					});
				} else {
					$.alert({ content: response.msg });
				}
			});
		}

		
		/* ===== [ 激活日历 ] ===== */
		$("#use-calendar").calendar([ null, null, 0, 1 ]);


		/* ===== [ 生成头部导航 ] ===== */
		$.getJSON(www + "handler/live.aspx?t=menu&callback=?").done(function ( response ) {
			if ( response.status === "1" ) {
				var links = "";
				$.each(response.data, function ( i, v ) {
					links += '<a href="' + ( v.value || "javascript:void(0);" ) + '">' + v.key + '</a>';
				});
				var $nav = $("nav");
				$nav.html(links).children().eq($nav.attr("data-active") - 1).addClass("active");
				var $first = $(".public-button").first();
				if ( $.cookie("qddfxf_login_state") === "ok" ) {
					$first.hide().next().show();
				} else {
					$first.show().next().hide();
				}

				// 输出头像下拉框
				$(".app-header > section").html($.cookie("qddfxf_loginout_menu")).children().last().on("click", function () {

					// 退出登录
					$.loginOut();
				});
			}
		});


		/* ===== [ 首页 ] ===== */
		if ( Dom("#page-index") ) {

			// 自动生成 "课程名称"
			$.getJSON(www + "handler/live.aspx?t=course&callback=?").done(function ( response ) {
				if ( response.status === "1" ) {

					// 生成内容
					new Vue({
						el: ".index-name",
						data: {
							list: response.data
						},
						methods: {

							// 点击 "课程名称" 切换 "课程列表"
							changeList: function ( event ) {
								var $target = $(event.target);
								if ( $target.is("span:not(.active)") ) {
									$(".index-name").find(".active").removeClass("active");
									$target.addClass("active");

									// 生成 "课程列表"
									create_list( $target.attr("data-id") );
								}
							}
						}
					});
				}
			});

			// 生成 "课程列表" 函数
			var list_template = $(".index-list").html();
			var create_list = function ( id ) {
				$.getJSON(www + "handler/live.aspx?t=seelist&callback=?", { 
					k: id 
				}).done(function ( response ) {
					if ( response.status === "1" ) {

						// 模板重置
						$(".index-list").empty().html(list_template);

						// 生成内容
						new Vue({
							el: ".index-list",
							data: {
								list: response.data
							},
							mounted: function () {
								$.imgError( $(".index-list").find("img") );
							}
						});
					} else {

						// 无数据时显示文字提示信息
						$(".index-list").empty().html('<p style="padding-top:20px;" class="no-data-tip">' + response.msg + '</p>');
					}
				});
			}

			// 自动生成 "全部" 对应的 "课程列表" 
			create_list(99999999);
		}


		/* ===== [ 录播 ] ===== */
		if ( Dom("#page-free") ) {

			// 自动生成 "最近观看" 列表
			$.getJSON(www + "handler/live.aspx?t=seeredlist&callback=?").done(function ( response ) {
				if ( response.status === "1" ) {
					new Vue({
						el: ".free-lately",
						data: {
							list: response.data
						},
						mounted: function () {
							$.imgError( $(".free-lately").find("img") );
						}
					});
				}
			});

			// 获取地址栏中参数 id 的值
			// 将此 id 值做为参数发送一次请求
			// 根据返回的数据得到视频地址来自动更新播放器
			$.getJSON(www + "handler/live.aspx?t=seered&callback=?", {
				id: window.location.href.match(/livedetail\/([0-9]+)/)[1]
			}).done(function ( response ) {
				if ( response.status === "1" ) {
				    $("iframe").replaceWith('<iframe frameborder="0" scrolling="no" allowtransparency="true" src="' + response.data[0].path + '"></iframe>');
				}
			});
		}


		/* ===== [ 表单 ] ===== */
		if ( Dom("#page-form") ) {

		    var sending = false;

			if ( Dom(".form-reset") ) {
				if ( window.location.href.substr(-2) === "/s" ) {
					$(".form-reset > p").text("绑定学员");
					$("#form-submit").text("立即绑定");
				}
			}

			// 登录页选项卡切换
			$("#form-login-tab").on("click", "span:not(.active)", function () {
				$(this).addClass("active").siblings().removeClass("active");
				$(".form-button").last().toggle();
				$("input").val("");
				if ( !$("#form-login-tab .active").index() ) {
					$(".form-binding").show();
					$("#form-forget").attr("href", "fropwd");
				} else {
					$(".form-binding").hide();
					$("#form-forget").attr("href", "fropwd/t");
				}
			})

			// 错误信息提示
			var errorInfo = {
				empty:       "请将表单填写完整",
			    phoneEmpty:  "请填写手机号",
				phoneFormat: "请输入正确格式的手机号",
				pwdFormat:   "密码格式错误，长度应在 6-20 位之间且只能包含字母、数字、下划线等字符",
				pwdError:    "密码错误",
				unlikeness:  "两次输入的密码不同"
			};

			// 验证手机和密码格式
			var checkPhoneFormat = function (number) {
			    //return !!(number.match(/^[1][3,4,5,7,6,8,9][0-9]{9}$/));
			    return !!(number.match(/(13[0-9]|15[0-3|5-9]|18[0-9]|14[5|7]|17[0|1|3|5-8]|199|198|191|167|166)\d{8}|(5|6|9)\d{7}$/));
			} 
			var checkPasswordFormat = function ( password ) {
				return !!(password.match(/^\w{6,20}$/));
			}

			// 登录验证
			var check_login = function () {
				var name = $(".form-phone input").val();
				var password = $(".form-code input").val();

				// 验证为空
				if ( !name || !password ) {
					$.alert({ content: errorInfo.empty });
					return;
				}

				// 验证手机号格式
				if ( !checkPhoneFormat(name) ) {
					$.alert({ content: errorInfo.phoneFormat });
					return;
				}

				// 验证密码格式
				if ( !checkPasswordFormat(password) ) {
					$.alert({ content: errorInfo.pwdFormat });
					return;
				}

				// 正确情况下登录
				$.ajax({
					url: www + "handler/login.ashx",
					type: "POST",
					data: {
						a: "doLogin",
						u: name, 
						p: password,
						t: $("#form-login-tab .active").index()
					},
					dataType: "json"
				}).done(function ( response ) {
					if ( response.status === "1" ) {
						var data = response.data; 

						// 设置登录状态
						if ( !$.cookie("qddfxf_login_state") ) {
							$.cookie("qddfxf_login_state", "ok", { path: "/" });

							// 生成头像下拉框菜单
							var menu = "";
							$.each(data, function ( i, v ) {
								if ( i > 0 ) {
									menu += '<div><a href="' + data[i].url + '"><span>' + data[i].name + '</span></a></div>';
								}
							});
							menu = menu + '<div><a href="javascript:void(0);" id="login-out"><span>退出登录</span></a></div>';
							
							// 将下拉框内容写进 cookie 用于头部组件调取
							$.cookie("qddfxf_loginout_menu", menu, { path: "/" });

							// 登录成功后跳转到指定地址
							window.location.href = data[0].url;
						}
					} else {

						// 登录失败
						$.alert({ content: response.msg });
						return;
					}
				});
			}

			// 重置密码验证
			var check_reset = function (text) {
			    sending = false;
				var name = $(".form-phone input").val();
				var code = $(".form-code input").val();
				var pwd01 = $(".form-password-01 input").val();
				var pwd02 = $(".form-password-02 input").val();

				// 验证为空
				if ( !name || !code || !pwd01 || !pwd02 ) {
					$.alert({ content: errorInfo.empty });
					return;
				}

				// 验证手机号格式
				if ( !checkPhoneFormat(name) ) {
					$.alert({ content: errorInfo.phoneFormat });
					return;
				}

				// 验证密码格式
				if ( !checkPasswordFormat(pwd01) ) {
					$.alert({ content: errorInfo.pwdFormat });
					return;
				}

				// 验证两次密码是否相同
				if ( pwd01 !== pwd02 ) {
					$.alert({ content: errorInfo.unlikeness });
					return;
				}

				// 正确情况下进行密码重置
				var param = {
					a: "checkPhone",
					u: name, 
					c: code,
					p: pwd01
				};
				if ( window.location.href.indexOf("/fropwd/t") > 0 ) {
					param.t = "t";
				}
				$.ajax({
					url: www + "handler/login.ashx",
					type: "POST",
					data: param,
					dataType: "json"
				}).done(function ( response ) {
					if ( response.status === "1" ) {
						$.alert({ 
							btnText: "登录",
							content: (text === "立即重置" ? "密码修改成功" : "绑定成功"),
							customFn: function () {
								window.location.href = "/login";
							}
						});
						window.setTimeout(function () {
							window.location.href = "/login";
						}, 3000);
					} else {
						$.alert({ content: response.msg });
						return;
					}
				});
			}

			// 点击发送验证码按钮
			$(".form-send").on("click", function () {
				var $this = $(this);
				var name = $(".form-phone input").val();

				if ( $this.hasClass("form-cannot-send") ) {
					return;
				}

				// 验证为空
				if ( !name ) {
					$.alert({ content: errorInfo.phoneEmpty });
					return;
				}

				// 验证手机号格式
				if ( !checkPhoneFormat(name) ) {
					$.alert({ content: errorInfo.phoneFormat });
					return;
				}

				// 手机号符合要求的情况下
				$.ajax({
					url: www + "handler/login.ashx",
					type: "POST",
					data: {
						a: "checkPhoneSCC",
						u: name,
						t: (window.location.href.indexOf("/fropwd/t") > 0 ? "t" : "")
					},
					dataType: "json"
				}).done(function ( response ) {
					if ( response.status === "1" ) {
						if ( $this.hasClass("form-cannot-send") ) {
							return;
						}

						// 发送验证码后按钮的状态
						$this.addClass("form-cannot-send").text("60秒后重新发送");
						var time = 60;
						var interval;
						var countDown = function () {
							if ( time > 1 ) {
								time--;
								$this.text(time + "秒后重新发送");
							} else {
								window.clearInterval(interval);
								$this.removeClass("form-cannot-send").text("发送验证码");
								time = 60;
							}
						}
						interval = window.setInterval(countDown, 1000);
					} else {
						$.alert({ content: response.msg });
						$(".form-phone input").val("");
						return;
					}
				});
			});

			// 点击登录按钮
			$("#form-login").on("click", function () {
				check_login();
			});

		    // 点击重置密码按钮
			$("#form-submit").on("click", function () {
			    if (!sending) {
			        sending = true;
			        check_reset($(this).text());
			    }
			});

			// 按下回车键提交
			$.enter(function () {
				$(".form-login").length ? check_login() : check_reset();
			});
		}


		/* ===== [ 学生端 - 改变直播按钮文字和状态 ] ===== */
		var ChangeButton = function ( selector, data ) {
			$(selector).find(".play").each(function ( i ) {
				var text = $(this).children().text();
				if ( text === "直播中" ) {
					$(this).addClass("active").next().text("立即观看").addClass("active").attr("href", data[i].liveurl);
				} else {
					$(this).next().text("查看回放").attr("href", data[i].playback_url).css({
						background: "#d7000f",
						cursor: "pointer"
					});
					if ( !data[i].playback_url ) {
						$(this).next().hide();
					}
					//$(this).next().text(text).attr("href", "javascript:void(0);");
				}
			});
		}


		/* ===== [ 学生端 - 今日课程 ] ===== */
		if ( Dom("#page-student-today") ) {

			// 登录状态判断
		    loginStatus();

		    // "进入直播间" 按钮显示
		    var $link = $("a.livelink");
		    $(".today-player").on({
		    	mouseenter: function () {
		    		$link.show();
		    	},
		    	mouseleave: function () {
		    		$link.hide();
		    	}
		    });

		    var n = 0;

			// 学习进度
			$.getJSON(www + "handler/stu_live.aspx?t=getmylearpro&callback=?").done(function ( response ) {
				new Vue({
					el: "#today-progress",
					data: {
						name: response.name,
						list: response.data
					}
				});
				n++;
			});

			// 课程表
			$.getJSON(www + "handler/stu_live.aspx?t=getcourselist&callback=?").done(function ( response ) {
				new Vue({
					el: "#today-schedule",
					data: {
						name: response.name,
						list: response.data
					}
				});
				n++;
			});

			// "学习进度" 和 "课程表" 选项卡的点击切换
			$("#today-switch").on("click", "span", function () {
				$(this).addClass("active").siblings().removeClass("active");
				$(".today-tab").eq($(this).index()).show().siblings(".today-tab").hide();
			});

		    // 进入直播间
			var check;
			function checkN() {
			    if ( n == 2 ) {
			        window.clearInterval(check);
			        var $iframe = $("#iframe");
			        $.getJSON(www + "handler/stu_live.aspx?t=todaylive&callback=?").done(function ( response ) {
			        	if ( response.status === "1" ) {
			        		$("#iframe").show().attr("src", response.data[0].imgsrc).css({
			        			width: "100%",
			        			height: "100%"
			        		});
			        		$("a.livelink").attr("href", response.data[0].liveurl);
			        	} else {
			        		$(".today-player").html(response.msg);
			        	}
			        });
			    }
			}
			check = window.setInterval(checkN, 16);
			
			// 视频播放器 "收起" 按钮
			var $player = $(".today-player");
			var $list = $(".today-list");
			var duration = 300;
			$(".today-player-fold").on("click", function () {
				var $this = $(this);
				if ( !$player.is(":animated") ) {
					if ( !$this.hasClass("folded")  ) {
						$list.animate({
							marginRight: "-320px"
						}, duration);
						$player.animate({
							width: "1200px"
						}, duration, function () {
							$this.addClass("folded");
							var hidden = !!($(".today-tab:hidden").index() === 1);
							$this.text(hidden ? "课表" : "进度").addClass(hidden ? "schedule" : "progress");
						});
					} else {
						$player.animate({
							width: "880px"
						}, duration, function () {
							$this.removeClass("folded schedule progress").text("收起");
						});
						$list.animate({
							marginRight: 0
						}, duration);
					}
				}
			});

			// 今日课程 [ 下方滚动容器 ]
			$.getJSON(www + "handler/stu_live.aspx?t=todaylist&callback=?").done(function ( response ) {
				if ( response.status === "1" ) {
					new Vue({
						el: ".today-scroll",
						data: {
							list: response.data
						},
						mounted: function () {
							$.imgError($(".today-scroll").find("img"));
							var $refresh = $("#need-refresh");

							// 手动修改按钮文字和状态
							ChangeButton($refresh, response.data);

							// 滚动动画
							var $scroll = $(".today-scroll > section > div");
							var liveSize = $scroll.find("li").length;
							var $left = $(".today-scrolleft");
							var $right = $(".today-scrollright");
							var basicWidth = 260;
							$scroll.width(liveSize * basicWidth).data("index", 0);
							var liveScroll = function ( i ) {
								if ( !$scroll.is(":animated") ) {
									$scroll.animate({
										marginLeft: -i * basicWidth + "px"
									}, function () {
										$scroll.data("index", i);
									});
								}
							}
							$right.on("click", function () {
								var index = $scroll.data("index");
								index++;
								if ( index < liveSize - 3 ) {
									liveScroll(index);
								}
							});
							$left.on("click", function () {
								var index = $scroll.data("index");
								index--;
								if ( index >= 0 ) {
									liveScroll(index);
								}
							});

							// 实时刷新
							var timer = null;
							var $li = $refresh.find("li");
							!(function ajaxInit () {
								var thisAjax = $.getJSON(www + "handler/stu_live.aspx?t=todayrefresh&callback=?").done(function ( response ) {

									// 遍历查询数据更改状态信息和按钮文字
									$.each(response.data, function ( item, every ) {
										var status = every.livestatus;
										var playing = !!(status === "直播中");
										$li.eq(item).find(".play span").text(status).parent().addClass(playing ? "active" : "").removeClass(!playing ? "active" : "");
										$li.eq(item).find("a").text(playing ? "立即观看" : status).attr("href", every.liveurl || "javascript:void(0);").addClass(playing ? "active" : "").removeClass(!playing ? "active" : "");
									});

									// 请求成功后关闭本次请求
									thisAjax.abort();

									// 定时器重置
									window.clearTimeout(timer);

									// 3s 后重新发送请求
									timer = window.setTimeout(function () {
										ajaxInit();
									}, 3000);
								});
							})();
						}
					});
				} else {

					// 无数据时的提示信息
					$(".today-scroll > section > div").empty().html(response.msg).removeAttr("hidden").width(1040).height(200).css({
						fontSize: "18px",
						fontWeight: "bold",
						textAlign: "center",
						lineHeight: "280px"
					}).parent().siblings("i").css({
						cursor: "not-allowed",
						opacity: .5
					});
				}
			});
		}


		/* ===== [ 学生端 - 全部课程 ] ===== */
		if ( Dom("#page-student-all") ) {

			// 登录状态判断
			loginStatus();

			// 缓存模板
			var template = $(".all-wrapper > ul").html();

			$.getJSON(www + "handler/stu_live.aspx?t=getothercourselist&callback=?").done(function ( response ) {
				if ( response.status === "1" ) {
					var data = response.data;
					$(".all-wrapper").addClass("noData");

					// 生成第一页数据
					new Vue({
						el: ".all-wrapper",
						data: {
							list: data
						},
						mounted: function () {
							$.imgError($(".all-wrapper").find("img"));

							// 修改按钮文字
							ChangeButton($(".all-wrapper"), data);

							// 激活分页功能
							$(".page-plugin").page({
								container: ".all-wrapper > ul",
								url: function ( page ) {
									return www + "handler/stu_live.aspx?t=getothercourselist&pg=" + page + "&callback=?";
								},
								total: response.pagecount,
								every: data.length,
								success: function () {
									return template;
								}
							});


						}
					});
				} else {
					$(".all-wrapper").empty().addClass("noData").html('<p style="padding-top:240px;" class="no-data-tip">' + response.msg + '</p>');
				}
			});
		}
		

		$body.show();

	})

})( window, document, jQuery, Vue );
